<template>
  <el-dialog
    :title="dataForm.id? $t('outlet.edit'): $t('outlet.add')"
    :close-on-click-modal="false"
    :visible.sync="visible"
    top="5vh"
    class="natice-dialog"
  >
    <el-form @submit.native.prevent  ref="dataForm" :rules="rules" :model="dataForm" label-position="right" size="small" label-width="90px" style="margin: 0 20px;">
      <!-- 公告标题 -->
      <el-form-item :label="$t('shop.announcementTitle')" prop="title">
        <el-input v-model="dataForm.title" :placeholder="$t('notice.preTitle')" show-word-limit maxlength="30" />
      </el-form-item>
      <!-- 发送时间 -->
      <el-form-item :label="$t('platform.sendTime')" prop="type">
        <el-radio-group v-model="dataForm.immediatelySend">
          <el-radio :label="1">{{$t('notice.sendTxt')}}</el-radio>
          <el-radio :label="0">{{$t('notice.timed')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 选择时间 -->
      <el-form-item v-show="dataForm.immediatelySend === 0" :label="$t('platform.selectTime')" prop="type">
        <el-date-picker
          v-model="dataForm.publishTime"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetime"
          :placeholder="$t('notice.preSendTime')"
          :picker-options="pickerOptions"
        />
      </el-form-item>
      <!-- 公告类型 -->
      <el-form-item :label="$t('notice.noticeType')" prop="type">
        <el-checkbox-group v-model="dataForm.receiverSysTypes" @change="ModeRecover">
          <!-- 门店 -->
          <el-checkbox :label="1">{{$t('shopProcess.shop')}}</el-checkbox>
          <!-- 承租商 -->
          <el-checkbox :label="3">{{$t('shopProcess.brand')}}</el-checkbox>
          <!-- 用户 -->
          <el-checkbox :label="0">{{$t('publics.user')}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <!-- 承租商范围 -->
      <el-form-item
        v-show="dataForm.receiverSysTypes.includes(3)"
        :label="$t('notice.brandRange')"
        prop="type"
      >
        <el-radio-group v-model="dataForm.receiveBrandMode">
          <el-radio :label="0">{{$t('notice.allBrand')}}</el-radio>
          <el-radio :label="1">{{$t('notice.designatedBrand')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <notice-select-account-range
        v-if="dataForm.receiveBrandMode == 1 && dataForm.receiverSysTypes.includes(3)"
        :table-list="dataForm.noticeBrandList"
        :type="2"
        @getIds="(ids) => dataForm.selectedBrandIds = ids"
      />

      <!-- 门店范围 -->
      <el-form-item
        v-show="dataForm.receiverSysTypes.includes(1)"
        :label="$t('notice.shopRang')"
        prop="type"
      >
        <el-radio-group v-model="dataForm.receiveShopMode">
          <el-radio :label="0">{{$t('notice.allStore')}}</el-radio>
          <el-radio :label="1">{{$t('notice.designatedShop')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <notice-select-account-range
        v-if="dataForm.receiveShopMode == 1 && dataForm.receiverSysTypes.includes(1)"
        :table-list="dataForm.noticeShopList"
        :type="1"
        @getIds="(ids) => dataForm.selectedShopIds = ids"
      />

      <!-- 用户范围 -->
      <el-form-item
        v-show="dataForm.receiverSysTypes.includes(0)"
        :label="$t('shop.userScope')"
        prop="type"
      >
        <el-radio-group v-model="dataForm.receiveUserMode">
          <el-radio :label="0">{{$t('shop.allUsers')}}</el-radio>
          <el-radio :label="1">{{$t('shop.specifyUser')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <notice-select-account-range
        v-if="dataForm.receiveUserMode == 1 && dataForm.receiverSysTypes.includes(0)"
        :table-list="dataForm.noticeUserList"
        :type="3"
        @getIds="(ids) => dataForm.selectedUserIds = ids"
      />

      <!-- 状态(1:公布 0:撤回) -->
      <el-form-item :label="$t('brand.status')" prop="status">
        <el-radio-group v-model="dataForm.status">
          <el-radio :label="1">{{$t('publics.publicar')}}</el-radio>
          <el-radio :label="0">{{$t('publics.cancel')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 是否置顶 -->
      <el-form-item :label="$t('product.isTop')" prop="isTop">
        <el-radio-group v-model="dataForm.isTop">
          <!-- 否 -->
          <el-radio :label="0">{{$t('shopProcess.no')}}</el-radio>
          <!-- 是 -->
          <el-radio :label="1">{{$t('shopProcess.yes')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 公告内容 -->
      <el-form-item :label="$t('shop.noticeContent')" prop="content">
        <tiny-mce ref="tinyMce" v-model="dataForm.content" v-if="visible" :tinymceHeight="250"></tiny-mce>
      </el-form-item>
    </el-form>
    <!-- 操作 -->
    <div slot="footer" class="dialog-footer">
      <!-- 取消 -->
      <el-button size="small" @click="visible = false">
        {{ $t('chat.cancel') }}
      </el-button>
      <!-- 确定 -->
      <el-button type="primary" size="small" @click="dataFormSubmit()">
        {{ $t('chat.confirm') }}
      </el-button>
    </div>
  </el-dialog>
</template>

<script>
import TinyMce from '@/components/tiny-mce'
import { Debounce } from '@/utils/debounce'
import { validNoEmptySpace, isHtmlNull } from '@/utils/validate'
import NoticeSelectAccountRange from './notice-select-account-range'
export default {
  components: {
    TinyMce,
    NoticeSelectAccountRange
  },
  data () {
    var validateTitle = (rule, value, callback) => {
      if (validNoEmptySpace(value)) {
        callback(new Error(this.$i18n.t('notice.contentNoNull')))
      } else {
        callback()
      }
    }
    var validateContent = (rule, value, callback) => {
      if (isHtmlNull(value)) {
        callback(new Error(this.$i18n.t('notice.contentNoNull')))
      } else {
        callback()
      }
    }
    return {
      pickerOptions: {
        // 设置禁用状态，参数为当前日期
        disabledDate (time) {
          // return time.getTime() < Date.now(); //当天不可选
          return time.getTime() < new Date().getTime() - 86400000 //  - 86400000是否包括当天
        },
        // 控制时分秒不可选
        selectableRange: (() => {
          const data = new Date()
          const hour = data.getHours()
          const minute = data.getMinutes()
          const second = data.getSeconds()
          return [`${hour}:${minute}:${second} - 23:59:59`]
        })()
      },
      visible: false,
      dataForm: {
        id: 0, // 公告id
        title: '', // 公告标题
        content: '', // 公告内容
        status: 1, // 状态(1:公布 0:撤回)
        isTop: 0, // 是否置顶
        publishTime: '', // 发送时间
        receiverSysTypes: [], // 接收者系统类型 1.商家端 3.承租商端 0.用户系统
        immediatelySend: 1, // 是否立即发送

        // 0:全部可见 1:指定可见
        receiveBrandMode: 1, // 承租商接收模式
        receiveShopMode: 1, // 门店接收模式
        receiveUserMode: 1, // 用户接收模式

        selectedBrandIds: [], // 承租商id集合
        selectedShopIds: [], // 门店id集合
        selectedUserIds: [] // 用户id集合

      },
      rules: {
        title: [
          { required: true, message: this.$t('notice.preTitle'), trigger: 'blur' },
          { validator: validateTitle, trigger: 'blur' }
        ],
        content: [
          { required: true, message: this.$t('notice.enterNotice'), trigger: 'blur' },
          { validator: validateContent, trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    init (id) {
      this.dataForm.id = id || 0
      this.dataForm.isTop = 0
      this.dataForm.status = 1
      this.dataForm.publishTime = ''
      this.dataForm.receiverSysTypes = []
      this.dataForm.immediatelySend = 1

      this.dataForm.receiveBrandMode = 0
      this.dataForm.receiveShopMode = 0
      this.dataForm.receiveUserMode = 0

      this.dataForm.selectedBrandIds = []
      this.dataForm.selectedShopIds = []
      this.dataForm.selectedUserIds = []

      // 承租商集合
      this.dataForm.noticeBrandList = []
      // 门店集合
      this.dataForm.noticeShopList = []
      // 用户集合
      this.dataForm.noticeUserList = []

      this.visible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].resetFields()
        if (!this.dataForm.id) return
        this.editInit()
      })
    },
    /**
     * 编辑页 触发
     */
    editInit () {
      this.$http({
        url: this.$http.adornUrl('/platform/notice/info/' + this.dataForm.id),
        method: 'get',
        params: this.$http.adornParams()
      }).then(({ data }) => {
        this.dataForm = data

        this.$set(this.dataForm, 'receiverSysTypes', this.dataForm.receiverSysTypes.split(',').map(Number))
        this.$set(this.dataForm, 'receiveShopMode', 0)
        this.$set(this.dataForm, 'receiveBrandMode', 0)
        this.$set(this.dataForm, 'receiveUserMode', 0)

        if (!this.dataForm.noticeShopList) {
          this.$set(this.dataForm, 'noticeShopList', [])
          this.$set(this.dataForm, 'selectedShopIds', [])
        } else {
          this.$set(this.dataForm, 'selectedShopIds', this.dataForm.noticeShopList.map(item => item.shopId))
        }

        if (!this.dataForm.noticeBrandList) {
          this.$set(this.dataForm, 'noticeBrandList', [])
          this.$set(this.dataForm, 'selectedBrandIds', [])
        } else {
          this.$set(this.dataForm, 'selectedBrandIds', this.dataForm.noticeBrandList.map(item => item.brandId))
        }

        if (!this.dataForm.noticeUserList) {
          this.$set(this.dataForm, 'noticeUserList', [])
          this.$set(this.dataForm, 'selectedUserIds', [])
        } else {
          this.$set(this.dataForm, 'selectedUserIds', this.dataForm.noticeUserList.map(item => item.userId))
        }

        this.dataForm.receiverSysTypes.forEach(type => {
          if (type === 1 && this.dataForm.noticeShopList.length > 0) {
            this.$set(this.dataForm, 'receiveShopMode', 1)
          }
          if (type === 3 && this.dataForm.noticeBrandList.length > 0) {
            this.$set(this.dataForm, 'receiveBrandMode', 1)
          }
          if (type === 0 && this.dataForm.noticeUserList.length > 0) {
            this.$set(this.dataForm, 'receiveUserMode', 1)
          }
        })

        this.$refs.tinyMce.setContent(data.content || '')
      })
    },

    // 表单提交
    dataFormSubmit: Debounce(function () {
      this.$refs.dataForm.validate(valid => {
        if (!valid) return
        if (this.dataForm.content && this.getText(this.dataForm.content).length > 20000) {
          this.$message({
            message: this.$t('notice.contentMore'),
            type: 'error',
            duration: 1500
          })
          return
        }

        if (this.dataForm.immediatelySend === 0 && !this.dataForm.publishTime) {
          this.$message({
            // 输入选择发送时间
            message: this.$t('notice.preSendTime'),
            type: 'error',
            duration: 1500
          })
          return
        }
        if (this.dataForm.receiverSysTypes.length === 0) {
          this.$message({
            // 请选择公告类型
            message: this.$t('notice.selectTypeTxt'),
            type: 'error',
            duration: 1500
          })
          return
        }
        if (this.dataForm.receiveShopMode === 1 && !this.dataForm.selectedShopIds.length) {
          this.$message({
            // 请选择指定门店
            message: this.$t('notice.selectShop'),
            type: 'error',
            duration: 1500
          })
          return
        }
        if (this.dataForm.receiveBrandMode === 1 && !this.dataForm.selectedBrandIds.length) {
          this.$message({
            // 请选择指定承租商
            message: this.$t('notice.selectBrand'),
            type: 'error',
            duration: 1500
          })
          return
        }
        if (this.dataForm.receiveUserMode === 1 && !this.dataForm.selectedUserIds.length) {
          this.$message({
            // 请选择指定用户
            message: this.$t('notice.selectUser'),
            type: 'error',
            duration: 1500
          })
          return
        }

        // 默认全选
        if (this.dataForm.receiveShopMode === 0) {
          this.dataForm.selectedShopIds = []
        }
        if (this.dataForm.receiveBrandMode === 0) {
          this.dataForm.selectedBrandIds = []
        }
        if (this.dataForm.receiveUserMode === 0) {
          this.dataForm.selectedUserIds = []
        }
        const obj = JSON.parse(JSON.stringify(this.dataForm))

        obj.receiverSysTypes = obj.receiverSysTypes.length > 0 ? obj.receiverSysTypes.join(',') : null
        obj.selectedShopIds = obj.selectedShopIds.length > 0 ? obj.selectedShopIds.join(',') : null
        obj.selectedBrandIds = obj.selectedBrandIds.length > 0 ? obj.selectedBrandIds.join(',') : null
        obj.selectedUserIds = obj.selectedUserIds.length > 0 ? obj.selectedUserIds.join(',') : null
        this.handlingAnnouncement(obj)
      })
    }, 1500),

    /**
     * 创建/修改 公告
     * @param {object} formData
     */
    handlingAnnouncement (formData) {
      this.$http({
        url: this.$http.adornUrl('/platform/notice'),
        method: formData.id ? 'put' : 'post',
        data: this.$http.adornData(formData)
      }).then(({ data }) => {
        this.$message({
          message: this.$t('outlet.success'),
          type: 'success',
          duration: 1500,
          onClose: () => {
            this.visible = false
            this.$emit('refreshDataList')
            this.$refs['dataForm'].resetFields()
          }
        })
      })
    },
    /**
     * 类型状态数据初始化
     * @param {*} e 选择公告类型
     */
    ModeRecover (e) {
      if (e && e.length === 0) return
      if (e.indexOf(3) === -1) this.dataForm.receiveBrandMode = 0
      if (e.indexOf(1) === -1) this.dataForm.receiveShopMode = 0
      if (e.indexOf(0) === -1) this.dataForm.receiveUserMode = 0
    },
    /**
     * 获取富文本中的行内文字(文字&英文&数字)
     * @param {*} str
     */
    getText (str) {
      return str
        .replace(/<[^<>]+>/g, '')
        .replace(/&nbsp;/gi, '')
        .replace(/(\s)+/gi, '')
    }
  }
}
</script>

<style lang="scss">
.natice-dialog {
  .el-dialog {
    min-width: 740px;
  }
  .el-dialog__body {
    padding: 10px 20px;
  }
}
</style>
